<?php


class DefaultController extends AppController {

	public $name = 'default';
	
	function beforeFilter() {
 	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('index1','index','shop','album','join','news','supplier','productlist','productlist1','city','getareas'); 

	}
	
	public function index1() {
        define("DIV_START_VIEW",1);	
    }	
	
	
	public function index() {
	    if(isset($this->my->groupid) && $this->my->groupid==4) {
		    define("DIV_START_VIEW",1);	
		}
        $city	= intval(Request::get_args("city"));		
		if(empty($city)){
            $city = $this->C_session->read('_user_city_id');
        }
		if(empty($city)){
            $city = 98;
        }	
		$query = array(
			'fields' => array('shopcategories.*'), 
			'order' => 'sort_order asc,id asc',
		);
		$result = POP::exe('[@@:UM shopcategories][@@:QU find:all]',$query);		
	    $CATEGORY1 = array();
	    $cat_info1 = array();
	    foreach($result as $v) {
		    $CATEGORY1[$v['shopcategories']['parent_id']][$v['shopcategories']['id']] = $v['shopcategories'];
		    $cat_info1[$v['shopcategories']['id']] = $v['shopcategories'];
	    }
	    $this->set('CATEGORY1',$CATEGORY1);		
		
		$query = array(
			'fields' => array('goodscategories.*'), 
			'order' => 'sort_order asc,id asc',
		);
		$result = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);		

        $CATEGORY = array();
        foreach($result as $v) {
	        $CATEGORY[$v['goodscategories']['parent_id']][$v['goodscategories']['id']] = $v['goodscategories'];
        }
		
		$query = array(
				'fields' => array('area.*'),
				'conditions' =>array('area.parent_id' => $city)
				);	
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);			
		$cityids = array();
		foreach($return_array as $val ) {
		    $cityids[$val['area']['id']] = $val['area']['id'];
		}
		$query = array(
				'fields' => array('area.*'),
				'conditions' =>array('area.area_type' => array(4),'area.parent_id' => $cityids)
				);	
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);			
		$areas_info = $return_array;
	    $this->set('areas_info', $areas_info);  		
	    $this->set('CATEGORY',$CATEGORY); 
	}	
	
	public function getareas() {	
        $parent_id = intval($_POST['value']);
        $type = intval($_POST['type']);
        $mode = $_POST['mode'];
        $pre = $_POST['pre'];		
        if(!$parent_id) {
	        exit();
        }
        if($type<0 || $type>2 || empty($mode)) {
	        exit();
        }		
		$query = array(
				'conditions' => array('area.parent_id' => $parent_id), 
				'fields' => array('area.*'), 
				);	
	    $areas_info = POP::exe('[@@:UM area][@@:QU find:all]',$query);	
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));		
        $select = "";
        if($type==0) {
	        $select .= '<select name="province"   onchange="areachanged(this.value,1);">';
	        $select .= '<option value="0">请选择省份...</option>';
        } elseif($type==1) {
	        $select .= '<select name="city"   onchange="areachanged(this.value,2);">';
	        $select .= '<option value="0">请选择城市...</option>';
        }
        foreach($areas_info as $v) {
	        $select .= '<option value="' . $v['area']['id'] . '">' . $v['area']['area_name'] . '</option>';
        } 
        $select .= '</select>';
        echo $select;
		exit;

	}	
	
	public function city() {
        $do = Request::get_args("do");			
		if($do =='do') {
            $cityid = intval(Request::get_args("id"));
            if(empty($cityid)) {
	            $this->C_session->write('_user_city_id', '0');
				echo '<script >alert("切换成功!");parent.location.reload();</script>';
				exit;
            }	
			$query = array(
					'fields' => array('area.*'),
					'conditions' =>array('area.id' =>$cityid )
					);	
			$array = POP::exe('[@@:UM area][@@:QU find:first]',$query);				
			if($array) {	
	            $this->C_session->write('_user_city_id', $cityid);
				echo '<script >alert("切换成功!");parent.location.reload();</script>';
				exit;
				//$this->flash("", Router::url('default/index'));
			}			
		}else {
		
		    //$this->flash("切换失败!", Router::url('default/index'));
		}
		$query = array(
				'fields' => array('area.*'),
				'conditions' =>array('area.area_type' => array(1,2))
				);	
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);	
		$areas_info = $return_array;
	    $this->set('areas_info', $areas_info);       		
	}	
	
	public function shop() {
        $page=Request::get_args("page");	
        $k=Request::get_args("k");
        $brand_id = intval(Request::get_args("brand_id"));
        $cat_id = intval(Request::get_args("cat_id"));
        $country = intval(Request::get_args("country"));
        $province = intval(Request::get_args("province"));
        $city	= intval(Request::get_args("city"));
        $district = intval(Request::get_args("district")); 	
		if(empty($city)){
            $city = $this->C_session->read('_user_city_id');
        }
        $conditions = array();               		
	    if ($city) {
		    $conditions['shopinfo.shop_city'] = $city; 
	    }		
        //统计关键词
        if($k!="请输入你要搜索的关键字" && $k!=""){		
			Loader::import('lib.ctime');
			$ctime = new ctime();

			$query = array(
					'fields' => array('keywordcount.*'),
					'conditions' =>array('keywordcount.keywords' => $k)
					);	
			$id_row= POP::exe('[@@:UM keywordcount][@@:QU find:first]',$query);

	        if(empty($id_row)){
		        $time = $ctime->time_stamp();
		        if($k!="请输入你要搜索的关键字"){
		            $safeData = array();			        
		            $safeData['keywordcount']['keywords'] = $k;	
		            $safeData['keywordcount']['count'] = 1;	
		            $safeData['keywordcount']['day'] = 1;	
		            $safeData['keywordcount']['week'] = 1;	
		            $safeData['keywordcount']['month'] = 1;	
		            $safeData['keywordcount']['dataline'] = $time;			            		            		        
			        POP::exe('[@@:UM keywordcount][@@:QU save]',$safeData);	
		        }
	        }else{
		        $time = $ctime->time_stamp();
		        $id=$id_row['keywordcount']['id'];
		        $day_time=mktime(0,0,0,$ctime->custom('m'),$ctime->custom('d'),$ctime->custom('Y'));
		        $w=$ctime->custom('w');
		        $week_time=mktime(0,0,0,$ctime->custom('m'),$ctime->custom('d')-$w,$ctime->custom('Y'));
		        $month_time=mktime(0,0,0,$ctime->custom('m'),1,$ctime->custom('Y'));
		        $safeData = array();
		        $safeData['count +'] = 1;
		        $safeData['dataline'] = $time;		        		        
		        if($id_row['keywordcount']['dataline']>$day_time){
		            $safeData['day +'] = 1;		
		            $safeData['week +'] = 1;
		            $safeData['month +'] = 1;		            		            	        
		        }else if($id_row['keywordcount']['dataline']>$week_time){
		            $safeData['day'] = 1;		
		            $safeData['week +'] = 1;
		            $safeData['month +'] = 1;			        
		        }else if($id_row['keywordcount']['dataline']>$month_time){
		            $safeData['day'] = 1;		
		            $safeData['week'] = 1;
		            $safeData['month +'] = 1;				        
		        }else{
		            $safeData['day'] = 1;		
		            $safeData['week'] = 1;
		            $safeData['month'] = 1;			        
		        }
				$query  = array();		
				$query['keyid'] = $id;				
				$query['set']['keywordcount'] = $safeData;					
				POP::exe('[@@:UM keywordcount][@@:QU save]',$safeData);		        
	        }
        }

		$query = array(
				'fields' => array('shopcategories.*'),
				'order'=>'sort_order asc,id asc'
				);	
		$result = POP::exe('[@@:UM shopcategories][@@:QU find:all]',$query);		
	    $CATEGORY = array();
	    $cat_info = array();
	    $is_parent_id = false;
	    foreach($result as $v) {
		    if($v['shopcategories']['id']==$cat_id && $v['shopcategories']['parent_id']==0){
			    $is_parent_id = true;
			    break;
		    }
	    }
	    foreach($result as $v) {
		    $CATEGORY[$v['shopcategories']['parent_id']][$v['shopcategories']['id']] = $v['shopcategories'];
		    $cat_info[$v['shopcategories']['id']] = $v['shopcategories'];
	    }	

		$query = array(
				'fields' => array('area.*'),
				);	
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);

	    $areainfo = array();		
	    foreach($return_array as $key=>$v) {
		    $areainfo[$v['area']['id']] = $v['area']['area_name'];
	    }	
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];			
	
	    if($is_parent_id){
/* 		    $sql="SELECT s.id as shop_id,s.shop_name,s.user_id,s.shop_logo,s.shop_country,s.open_flg,s.lock_flg,s.shop_province,s.shop_district,
			s.shop_city,u.username as user_name,u.rank_id,ur.id as rank_id,ur.rank_name,s.goods_num,s.shop_domain 
			FROM imall_shop_info AS s 
			join imall_user AS u on s.user_id=u.id
			join imall_user_rank AS ur on u.rank_id=ur.id
			join (SELECT id as cat_id from imall_shop_categories where parent_id=$cat_id ) as sc  on s.shop_categories =sc.cat_id 
			WHERE s.lock_flg <>'1' and s.open_flg='0'"; */
	        $conditions['shopinfo.lock_flg <>'] = 1;
	        $conditions['shopinfo.open_flg'] = 0;	        
			$conditions['shopcategories.parent_id'] = $cat_id;
	        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	        $tb = array('model' => 'shopinfo',
	 		            'joins' => array(
						    array('type'=>'left','table'=>'user','conditions'=>array('shopinfo.user_id' =>'user.id')),
						    array('type'=>'left','table'=>'userrank','conditions'=>array('userrank.id' =>'user.rank_id')),	
						    array('type'=>'left','table'=>'shopcategories','conditions'=>array('shopinfo.shop_categories' =>'shopcategories.cat_id')),						    					    					
							),
					    'fields' => array("shopinfo.id,shopinfo.shop_name,shopinfo.user_id,shopinfo.shop_logo,shopinfo.shop_country,shopinfo.open_flg,shopinfo.lock_flg,shopinfo.shop_province,shopinfo.shop_district,shopinfo.shop_city,user.username as user_name,user.rank_id,userrank.id,userrank.rank_name,shopinfo.goods_num,shopinfo.shop_domain"),
						'conditions' => $conditions,
						'order' => '',
						'limit' => '10',
						'group' => '',
						'url' => preg_replace("/&page=([^&]+)/","",$url_this),
						'page' => $page,
						'plist' => 6				
					); 

	    }else if($cat_id){
/* 		    $sql="SELECT distinct s.id as shop_id,s.shop_name,s.user_id,s.shop_logo,s.shop_country,s.open_flg,s.lock_flg,s.shop_province,s.shop_district,
		s.shop_city,u.username as user_name,u.rank_id,ur.id as rank_id,ur.rank_name,s.goods_num,s.shop_domain 
		FROM $t_shop_info AS s,$t_user AS u,$t_user_rank AS ur,$t_shop_categories as sc ,$t_shop_request as sr
		WHERE sr.status=1 and sr.user_id=s.user_id and s.lock_flg <>'1' and s.open_flg='0' AND s.user_id=u.id AND u.rank_id=ur.id and s.shop_categories = sc.id and s.shop_categories=$cat_id";
 */

	        $conditions['shopinfo.lock_flg <>'] = 1;
	        $conditions['shopinfo.open_flg'] = 0;	        
			$conditions['shopinfo.shop_categories'] = $cat_id;
	        $conditions['shoprequest.status'] = 1;	        			
	        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	        $tb = array('model' => 'shopinfo',
	 		            'joins' => array(
						    array('type'=>'left','table'=>'user','conditions'=>array('shopinfo.user_id' =>'user.id')),
						    array('type'=>'left','table'=>'userrank','conditions'=>array('userrank.id' =>'user.rank_id')),	
						    array('type'=>'left','table'=>'shopcategories','conditions'=>array('shopinfo.shop_categories' =>'shopcategories.id')),
						    array('type'=>'left','table'=>'shoprequest','conditions'=>array('shoprequest.user_id' =>'shopinfo.user_id')),						    						    					    					
							),
					    'fields' => array("shopinfo.id,shopinfo.shop_name,shopinfo.user_id,shopinfo.shop_logo,shopinfo.shop_country,shopinfo.open_flg,shopinfo.lock_flg,shopinfo.shop_province,shopinfo.shop_district,shopinfo.shop_city,user.username,user.rank_id,userrank.id,userrank.rank_name,shopinfo.goods_num,shopinfo.shop_domain"),
						'conditions' => $conditions,
						'order' => '',
						'limit' => '10',
						'group' => '',
						'url' => preg_replace("/&page=([^&]+)/","",$url_this),
						'page' => $page,
						'plist' => 6				
					); 

		}else{
/* 		    $sql="SELECT distinct s.id as shop_id,s.shop_name,s.user_id,s.shop_logo,s.shop_country,s.open_flg,s.lock_flg,s.shop_province,s.shop_district,
		s.shop_city,u.username as user_name,u.rank_id,ur.id as rank_id,ur.rank_name,s.goods_num,s.shop_domain 
		FROM $t_shop_info AS s,$t_user AS u,$t_user_rank AS ur ,$t_shop_request as sr
		WHERE sr.status=1 and sr.user_id=s.user_id and s.lock_flg <>'1' and s.open_flg='0' AND s.user_id=u.id AND u.rank_id=ur.id"; */


	        $conditions['shopinfo.lock_flg <>'] = 1;
	        $conditions['shopinfo.open_flg'] = 0;	        
	        $conditions['shoprequest.status'] = 1;	        			
	        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	        $tb = array('model' => 'shopinfo',
	 		            'joins' => array(
						    array('type'=>'left','table'=>'user','conditions'=>array('shopinfo.user_id' =>'user.id')),
						    array('type'=>'left','table'=>'userrank','conditions'=>array('userrank.id' =>'user.rank_id')),	
						    array('type'=>'left','table'=>'shoprequest','conditions'=>array('shoprequest.user_id' =>'shopinfo.user_id')),						    						    					    					
							),
					    'fields' => array("shopinfo.id,shopinfo.shop_name,shopinfo.user_id,shopinfo.shop_logo,shopinfo.shop_country,shopinfo.open_flg,shopinfo.lock_flg,shopinfo.shop_province,shopinfo.shop_district,shopinfo.shop_city,user.username as user_name,user.rank_id,userrank.id,userrank.rank_name,shopinfo.goods_num,shopinfo.shop_domain"),
						'conditions' => $conditions,
						'order' => '',
						'limit' => '10',
						'group' => '',
						'url' => preg_replace("/&page=([^&]+)/","",$url_this),
						'page' => $page,
						'plist' => 6				
					); 	
		
	    }

	    if ($k&&$k!="请输入你要搜索的关键字") {
		    $goods_sql = "";
		
		    $k=str_replace("　"," ",$k);
		    $k=str_replace("'","\'",$k);
		    $k=str_replace("\"","\\\"",$k);
		    $k=str_replace("%","\%",$k);
		    $k=str_replace("#","\#",$k);
		    $k=addslashes($k);
		    $ks = explode(' ', $k);		
		    $n_conditions = array();
		    $k_conditions = array(); 
		
		    foreach($ks as $key) {
		        if (!empty($key)){
		            $n_conditions[] = "shopinfo.shop_name like '%$key%'";
		            $redks[]="<font color='red'>$key</font>";
		        }
		    }
		                
		    if (!empty($n_conditions) )	{   
		        $filter = '('.implode(' OR ', $n_conditions).')';
		        $tb['conditions'].=" AND $filter";
		    }
	    }
		//$tb['group'] = "shopinfo.id ASC";
 	    $result =  $this->fpage($tb);	
	    $k = urlencode($k);
	    $this->set('k',$k);
	    $this->set('keyworld',$k);		
	    $this->set('cat_id',$cat_id);	
	    $this->set('page',$page);			
	    $this->set('result',$result);			
	    $this->set('areainfo',$areainfo);
	    $this->set('CATEGORY',$CATEGORY);	
	    $this->set('province',$province);
	    $this->set('city',$city);	
	}
	public function album() {

	}	
	public function join() {

	}	
	public function news() {

	}	
	public function supplier() {
        $page=Request::get_args("page");	
        $k=Request::get_args("k");
        $brand_id = intval(Request::get_args("brand_id"));
        $cat_id = intval(Request::get_args("cat_id"));
        $country = intval(Request::get_args("country"));
        $province = intval(Request::get_args("province"));
        $city	= intval(Request::get_args("city"));
        $district = intval(Request::get_args("district")); 	
		if(empty($city)){
            $city = $this->C_session->read('_user_city_id');
        }
        $sql ="";		
	    if ($city) {
		    $sql.=" AND s.supi_city='$city' ";
	    }		


		$query = array(
				'fields' => array('shopcategories.*'),
				'order'=>'sort_order asc,id asc'
				);	
		$result = POP::exe('[@@:UM shopcategories][@@:QU find:all]',$query);
	
	    $CATEGORY = array();
	    $cat_info = array();
	    $is_parent_id = false;
	    foreach($result as $v) {
		    if($v['shopcategories']['id']==$cat_id && $v['shopcategories']['parent_id']==0){
			    $is_parent_id = true;
			    break;
		    }
	    }
	    foreach($result as $v) {
		    $CATEGORY[$v['shopcategories']['parent_id']][$v['shopcategories']['id']] = $v['shopcategories'];
		    $cat_info[$v['shopcategories']['id']] = $v['shopcategories'];
	    }

		$query = array(
				'fields' => array('area.*'),
				);	
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);

	    $areainfo = array();		
	    foreach($return_array as $key=>$v) {
		    $areainfo[$v['area']['id']] = $v['area']['area_name'];
	    }	
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];			
        $this->loadModel('supplierinfo');
	    if ($cat_id) {
		    $sql.=" AND s.supi_categories='$cat_id' ";
	    }		
	    if ($k) {
		    $sql.=" AND s.supi_name like '%$k%'";
	    }			
            $tb=array('table' => "".$this->supplierinfo->tablePrefix."supplier_info AS s,".$this->supplierinfo->tablePrefix."user AS u,".$this->supplierinfo->tablePrefix."user_rank AS ur,".$this->supplierinfo->tablePrefix."shop_categories as sc ", 
			'fields' =>"distinct s.*,u.username as user_name,u.rank_id,ur.id as rank_id,ur.rank_name",
			'conditions' => " s.supi_user_id=u.id AND u.rank_id=ur.id and s.supi_categories = sc.id ".$sql,
			'order' => '',
			'limit' => '10', 
            'group' => '',			
			'url' => preg_replace("/&page=([^&]+)/","",$url_this),
			'page' => $page,'plist' => 6,
			'startPage' => true,'DbConfig' => null
			) ;	
		


		$tb['group'] = " s.id ASC ";
 	    $result =  $this->fetch_page($tb);	
	    $k = urlencode($k);
	    $this->set('k',$k);
	    $this->set('keyworld',$k);		
	    $this->set('cat_id',$cat_id);	
	    $this->set('page',$page);			
	    $this->set('result',$result);			
	    $this->set('areainfo',$areainfo);
	    $this->set('CATEGORY',$CATEGORY);	
	    $this->set('province',$province);
	    $this->set('city',$city);	
	}	
	public function productlist($isbrand="") {

        $page=Request::get_args("page");	
        $k=Request::get_args("k");
        $suppid=Request::get_args("suppid");		
        $min_price = intval(Request::get_args("min_price"));
        $max_price = intval(Request::get_args("max_price"));		
        $brand_id = intval(Request::get_args("brand_id"));
        $up_price = intval(Request::get_args("up_price"));		
        $down_price = intval(Request::get_args("down_price"));
		
        $pv = intval(Request::get_args("pv"));
        $fpv = intval(Request::get_args("fpv"));
        $new = intval(Request::get_args("new"));		
		
        $cat_id = intval(Request::get_args("cat_id"));
        $country = intval(Request::get_args("country"));
        $province = intval(Request::get_args("province"));

        $city	= intval(Request::get_args("city"));
        $district = intval(Request::get_args("district"));	
		if(empty($city)){
            $city = $this->C_session->read('_user_city_id');
        }	

 		$query = array(
				'fields' => array('goodscategories.*'),
				'order'=>'sort_order asc,id asc'
				);	
		$result = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);
		       	
        $CATEGORY = array();
        $cat_info = array();
        foreach($result as $v) {
	        $CATEGORY[$v['goodscategories']['parent_id']][$v['goodscategories']['id']] = $v['goodscategories'];
        }
        foreach($result as $v) {
	        $cat_info[$v['goodscategories']['id']] = $v['goodscategories'];
        }
		
        //统计关键词
        if($k!="请输入你要搜索的关键字" && $k!=""){		
		    $this->loadModel('keywordcount');
			Loader::import('lib.ctime');
			$ctime = new ctime();

			$query = array(
					'fields' => array('keywordcount.*'),
					'conditions' =>array('keywordcount.keywords' => $k)
					);	
			$id_row= POP::exe('[@@:UM keywordcount][@@:QU find:first]',$query);
			
	        if(empty($id_row)){
		        $time = $ctime->time_stamp();
		        if($k!="请输入你要搜索的关键字"){
		            $safeData = array();			        
		            $safeData['keywordcount']['keywords'] = $k;	
		            $safeData['keywordcount']['count'] = 1;	
		            $safeData['keywordcount']['day'] = 1;	
		            $safeData['keywordcount']['week'] = 1;	
		            $safeData['keywordcount']['month'] = 1;	
		            $safeData['keywordcount']['dataline'] = $time;			            		            		        
			        POP::exe('[@@:UM keywordcount][@@:QU save]',$safeData);	
		        }
	        }else{
		        $time = $ctime->time_stamp();
		        $id=$id_row['keywordcount']['id'];
		        $day_time=mktime(0,0,0,$ctime->custom('m'),$ctime->custom('d'),$ctime->custom('Y'));
		        $w=$ctime->custom('w');
		        $week_time=mktime(0,0,0,$ctime->custom('m'),$ctime->custom('d')-$w,$ctime->custom('Y'));
		        $month_time=mktime(0,0,0,$ctime->custom('m'),1,$ctime->custom('Y'));
		        $safeData = array();
		        $safeData['count +'] = 1;
		        $safeData['dataline'] = $time;		        		        
		        if($id_row['keywordcount']['dataline']>$day_time){
		            $safeData['day +'] = 1;		
		            $safeData['week +'] = 1;
		            $safeData['month +'] = 1;		            		            	        
		        }else if($id_row['keywordcount']['dataline']>$week_time){
		            $safeData['day'] = 1;		
		            $safeData['week +'] = 1;
		            $safeData['month +'] = 1;			        
		        }else if($id_row['keywordcount']['dataline']>$month_time){
		            $safeData['day'] = 1;		
		            $safeData['week'] = 1;
		            $safeData['month +'] = 1;				        
		        }else{
		            $safeData['day'] = 1;		
		            $safeData['week'] = 1;
		            $safeData['month'] = 1;			        
		        }
				$query  = array();		
				$query['keyid'] = $id;				
				$query['set']['keywordcount'] = $safeData;					
				POP::exe('[@@:UM keywordcount][@@:QU save]',$safeData);	  
	        }
        }
		
	    /* 列表处理 */
	    if(!function_exists('getsubcats')) {
		    function getsubcats($catinfo, $id) {
			    $str = '';
			    if(isset($catinfo[$id]) && $catinfo[$id]) {
				    foreach($catinfo[$id] as $v) {
					    $str .= ",".$v['id'];
					    $str .= getsubcats($catinfo, $v['id']);
				    }
			    }
			    return $str;
		    }
	    }
	    if($cat_id){
		    $catids = $cat_id;
		    $catids .= getsubcats($CATEGORY, $cat_id);
		    $this_catinfo = $cat_info[$cat_id];
		    $this_parent_info = '';
		    if($cat_info[$cat_id]['parent_id']>0){
			    $this_parent_info = $cat_info[$cat_info[$cat_id]['parent_id']];
		    }
	    }
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];			
	    $this->loadModel('goods');	
        $tb=array('table' => " `".$this->goods->tablePrefix."goods` AS g,`".$this->goods->tablePrefix."user` AS u,`".$this->goods->tablePrefix."shop_info` AS s,`".$this->goods->tablePrefix."user_rank` AS ur ", 
			'fields' =>"g.pv,g.is_set_image,g.brand_id,g.transport_price,g.transport_template_price,g.goods_thumb,g.id as goods_id,g.cat_id,g.goods_name,g.goods_price,g.goods_intro,g.shop_id,g.goods_number,g.goods_refer_price,s.id as shop_id,s.shop_name,s.user_id,s.shop_country,s.shop_province,s.shop_district,s.shop_city,u.id as user_id,u.rank_id,ur.id as rank_id,ur.rank_name,
				s.shop_province,s.shop_city	",
			'conditions' => " g.lock_flg<>1 ",
			'order' => '',
			'limit' => '10', 
            'group' => '',			
			'url' => preg_replace("/&page=([^&]+)/","",$url_this),
			'page' => $page,'plist' => 6,
			'startPage' => true,'DbConfig' => null
		) ;	
		
/* 	    $sql="SELECT g.pv,g.is_set_image,g.brand_id,g.transport_price,g.transport_template_price,g.goods_thumb,g.id as goods_id,g.cat_id,g.goods_name,g.goods_price,g.goods_intro,g.shop_id,s.id as shop_id,s.shop_name,s.user_id,s.shop_country,s.shop_province,s.shop_district,s.shop_city,u.id as user_id,u.rank_id,ur.id as rank_id,ur.rank_name,
				s.shop_province,s.shop_city	FROM `$t_goods` AS g,`$t_user` AS u,`$t_shop_info` AS s,`$t_user_rank` AS ur WHERE g.lock_flg<>1 "; */
	    
		if ($brand_id && $isbrand!="brand") {
		    $tb['conditions'].="AND g.brand_id='$brand_id' ";
	    }
	    if ($min_price) {
		    $tb['conditions'].=" AND g.goods_price>'$min_price' ";
	    }
	    if ($max_price) {
		    $tb['conditions'].=" AND g.goods_price<'$max_price' ";
	    }
	    if ($province) {
		    $tb['conditions'].=" AND s.shop_province='$province' ";
	    }
	    if ($country) {
		    $tb['conditions'].=" AND s.shop_country='$country' ";
	    }
	    if ($city) {
		    $tb['conditions'].=" AND s.shop_city='$city' ";
	    }
	    if ($district) {
		    $tb['conditions'].=" AND s.shop_district='$district' ";
	    }	
		
	    if ($suppid) {
		    $tb['conditions'].=" AND g.supplier_user_id='$suppid' ";
	    }	
		
	    if ($up_price) {
		    $tb['order']=" g.goods_price asc ";
	    }	
	    if ($down_price) {
		    $tb['order']=" g.goods_price desc ";
	    }	
		
	    if ($pv) {
		    $tb['order']=" g.pv desc ";
	    }	
	    if ($fpv) {
		    $tb['order']=" g.favpv desc ";
	    }			
	    if ($new) {
		    $tb['order']=" g.id desc ";
	    }	
	
		
	    if ($k&&$k!="请输入你要搜索的关键字") {
		    $this->loadModel('tag');  
		    $tag_sql="SELECT distinct goods_id FROM ".$this->tag->tablePrefix."tag as t WHERE tag_name='$k'";
		    $tag_list = $this->tag->query($tag_sql);
		    foreach ($tag_list as $key=>$v){
			    $tag_list[$key]=$v['t']['goods_id'];
		    }
		    $goods_sql = "";
		    $k=str_replace("　"," ",$k);
		    $k=str_replace("'","\'",$k);
		    $k=str_replace("\"","\\\"",$k);
		    $k=str_replace("%","\%",$k);
		    $k=str_replace("#","\#",$k);
		    $k=addslashes($k);
		    $ks = explode(' ', $k);
		
		    $n_conditions = array();
		    $b_conditions = array();			
		    $k_conditions = array(); 
		
		    foreach($ks as $key){
		        if (!empty($key)) {
		            $n_conditions[] = "goods_name like '%$key%'";
		            $b_conditions[] = "brand_name like '%$key%'";					
		          //$k_conditions[] = "keyword like '%$key%'";
		            $redks[]="<font color='red'>$key</font>";
		        }
		    }
		                
		    if (!empty($n_conditions) ){
		        $filter = '('.implode(' OR ', $n_conditions).')';
		        $goods_sql = " WHERE $filter";
				$b_filter_sql = '('.implode(' OR ', $b_conditions).')';
		                        
		    //  $filter = '('.implode(' OR ', $k_conditions).')';
		    //  $goods_sql .= ' OR ' . $filter;
		    }
            if($isbrand=="brand") {
			    $sql="SELECT id FROM ".$this->goods->tablePrefix."brand as b WHERE $b_filter_sql ";
		        $row_list=$this->goods->query($sql);
		        foreach ($row_list as $key2=>$v2){
			        $row_list[$key2]=$v2['b']['id'];
		        }
		        $goods_ids=implode(",",$row_list);
		
		        if($row_list&&$tag_list){
			        $goods_ids=$goods_ids.",";
		        }
		        $goods_ids .= implode(",",$tag_list);
		        $arr = explode(",",$goods_ids);
		        $arr = array_unique($arr);
		        $goods_ids = implode(",",$arr);
		        if($goods_ids==""){
			        $goods_ids="0";
		        }
		        $tb['conditions'].=" AND g.brand_id IN ($goods_ids) ";				
		    } else {		                                
		        $goods_sql = "SELECT distinct id as goods_id FROM ".$this->goods->tablePrefix."goods as g" . $goods_sql;
		        $goods_list = $this->tag->query($goods_sql);
		        foreach ($goods_list as $key2=>$v2){
			        $goods_list[$key2]=$v2['g']['goods_id'];
		        }
		        $goods_ids=implode(",",$goods_list);
		
		        if($goods_list&&$tag_list){
			        $goods_ids=$goods_ids.",";
		        }
		        $goods_ids .= implode(",",$tag_list);
		        $arr = explode(",",$goods_ids);
		        $arr = array_unique($arr);
		        $goods_ids = implode(",",$arr);
		        if($goods_ids==""){
			        $goods_ids="0";
		        }
		        $tb['conditions'].=" AND g.id IN ($goods_ids) ";
			}
	    }		
	    if(isset($catids)) {
		    $tb['conditions'].=" AND g.cat_id IN ($catids)";
	    }
	    $tb['conditions'].="and g.is_on_sale=1 AND g.shop_id=s.id AND s.user_id=u.id AND u.rank_id=ur.id ";
		
		$query = array(
				'fields' => array('area.*'),
				);	
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);
	    $areainfo = array();		
	    foreach($return_array as $key=>$v) {
		    $areainfo[$v['area']['id']] = $v['area']['area_name'];
	    }	
	
 	    $result =  $this->fetch_page($tb);
	
	    $this->set('k',$k);
	    $this->set('keyworld',$k);		
	    $this->set('cat_id',$cat_id);	
	    $this->set('page',$page);			
	    $this->set('result',$result);			
	    $this->set('areainfo',$areainfo);
	    $this->set('CATEGORY',$CATEGORY);	
		
	    $this->set('min_price',$min_price);
	    $this->set('max_price',$max_price);
	    $this->set('province',$province);
	    $this->set('city',$city);
	    $this->set('suppid',$suppid);		
	}
	public function productlist1() {
        $page=Request::get_args("page");	
        $suppid=Request::get_args("suppid");		
        $min_price = intval(Request::get_args("min_price"));
        $max_price = intval(Request::get_args("max_price"));		
        $up_price = intval(Request::get_args("up_price"));		
        $down_price = intval(Request::get_args("down_price"));
		
        $pv = intval(Request::get_args("pv"));
        $fpv = intval(Request::get_args("fpv"));
        $new = intval(Request::get_args("new"));
		
        $country = intval(Request::get_args("country"));
        $province = intval(Request::get_args("province"));
        $city	= intval(Request::get_args("city"));
        $district = intval(Request::get_args("district"));	
		if(empty($city)){
            $city = $this->C_session->read('_user_city_id');
        }			
        $cat_id = intval(Request::get_args('id'));
		$cat_idd =$cat_id;
        if(empty($cat_id)) {
	        trigger_error("非法请求");
        }	
        $brand_id=Request::get_args("brand_id");
        $attr_arr = Request::get_args("attr");
		if(empty($city)){
            $city = $this->C_session->read('_user_city_id');
        }
        $sql ="";		
	    if ($city) {
		    $sql.=" AND s.shop_city='$city' ";
	    }	

 		$query = array(
				'fields' => array('goodscategories.*'),
				'order'=>'sort_order asc,id asc'
				);	
		$result = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);
	    		
        $CATEGORY = array();
        $cat_info = array();
        foreach($result as $v) {
	        $CATEGORY[$v['goodscategories']['parent_id']][$v['goodscategories']['id']] = $v['goodscategories'];
        }
        foreach($result as $v) {
	        $cat_info[$v['goodscategories']['id']] = $v['goodscategories'];
        }
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];			
        /* 列表处理 */
        if(!function_exists('getsubcats')) {
	        function getsubcats($catinfo, $id) {
		        $str = '';
		        if(isset($catinfo[$id]) && $catinfo[$id]) {
			        foreach($catinfo[$id] as $v) {
				        $str .= ",".$v['id'];
				        $str .= getsubcats($catinfo, $v['id']);
			        }
		        }
		        return $str;
	        }
        }
        if($cat_id){
	        $catids = $cat_id;
	        $catids .= getsubcats($CATEGORY, $cat_id);
	        $this_catinfo = $cat_info[$cat_id];
	        $this_parent_info = '';
	        if($cat_info[$cat_id]['parent_id']>0){
		        $this_parent_info = $cat_info[$cat_info[$cat_id]['parent_id']];
	        }
        }
        if(isset($attr_arr)&&$attr_arr){
	        foreach ($attr_arr as $k=>$v){
		        $attr_arr[$k]=$v;
		        $attr_id_arr[]="attr[".$k."]";
	        }
        }		
		$query = array(
				'fields' => array('area.*'),
				);	
		$return_array = POP::exe('[@@:UM area][@@:QU find:all]',$query);
	    $areainfo = array();		
	    foreach($return_array as $key=>$v) {
		    $areainfo[$v['area']['id']] = $v['area']['area_name'];
	    }	
	    $this->loadModel('goods');
        $get_arr = $_GET;
        $where  = "";
        $from = "";
        $and = '';
        foreach($get_arr as $k=>$value){
	        if(substr($k,0,4) == 'attr'){
		        $num = substr($k,4,strlen($k));
		        $and .= "g".$num.".goods_id and g".$num.".goods_id=";
		        $where .= " and g".$num.".attr_values = '$value'";
		        $from .= "".$this->goods->tablePrefix."goods_attr as g".$num.",";
	        }
        }		
	
        if($where){
	        $sta_num = strpos($and,'and');
	        $end_num = strrpos($and,'and');
	        $and = substr($and,$sta_num,$end_num-$sta_num);
	        $sql = "select * from ".substr($from,0,-1)." where g".$num.".attr_values != ''".$where." ".$and." group by g".$num.".goods_id";
	        $result = $this->goods->query($sql);
	        $goods_id = '';
	        foreach($result as $value){
		        $goods_id .= $value["g".$num]['goods_id'].",";
	        }
	        if($goods_id != ''){
		        $goods_id = substr($goods_id,0,-1);
	        }else{
		        $goods_id = 0;
	        }
/* 	        $sql = "SELECT g.pv,g.is_set_image,g.brand_id,g.transport_price,g.transport_template_price,g.goods_thumb,g.id as goods_id,g.cat_id,g.goods_name,g.goods_price,g.goods_intro,g.shop_id,s.id as shop_id,s.shop_name,s.user_id,u.id as user_id,u.rank_id,ur.id as rank_id,ur.rank_name,
			s.shop_province,s.shop_city	FROM `$t_goods` AS g,`$t_user` AS u,`$t_shop_info` AS s,`$t_user_rank` AS ur WHERE g.lock_flg<>1 and  
		g.id IN ($goods_id) and g.is_on_sale=1 AND g.shop_id=s.id AND s.user_id=u.id AND u.rank_id=ur.id "; */
		
            $tb=array('table' => "  `".$this->goods->tablePrefix."goods` AS g,`".$this->goods->tablePrefix."user` AS u,`".$this->goods->tablePrefix."shop_info` AS s,`".$this->goods->tablePrefix."user_rank` AS ur  ", 
			'fields' =>"g.pv,g.is_set_image,g.brand_id,g.transport_price,g.transport_template_price,g.goods_thumb,g.id as goods_id,g.cat_id,g.goods_name,g.goods_price,g.goods_intro,g.shop_id,g.goods_number,g.goods_refer_price,s.id as shop_id,s.shop_name,s.user_id,u.id as user_id,u.rank_id,ur.id as rank_id,ur.rank_name,s.shop_province,s.shop_city	",
			'conditions' => " g.lock_flg<>1 and g.id IN ($goods_id) and g.is_on_sale=1 AND g.shop_id=s.id AND s.user_id=u.id AND u.rank_id=ur.id ".$sql,
			'order' => '',
			'limit' => '10', 
            'group' => '',			
			'url' => preg_replace("/&page=([^&]+)/","",$url_this),
			'page' => $page,'plist' => 6,
			'startPage' => true,'DbConfig' => null
		    ) ;			
		
        }else{

            $tb=array('table' => "  `".$this->goods->tablePrefix."goods` AS g,`".$this->goods->tablePrefix."user` AS u,`".$this->goods->tablePrefix."shop_info` AS s,`".$this->goods->tablePrefix."user_rank` AS ur  ", 
			'fields' =>"g.pv,g.is_set_image,g.brand_id,g.transport_price,g.transport_template_price,g.goods_thumb,g.id as goods_id,g.cat_id,g.goods_name,g.goods_price,g.goods_intro,g.shop_id,g.goods_number,g.goods_refer_price,s.id as shop_id,s.shop_name,s.user_id,u.id as user_id,u.rank_id,ur.id as rank_id,ur.rank_name,s.shop_province,s.shop_city	",
			'conditions' => " g.lock_flg<>1 and g.cat_id IN ($catids) AND g.is_on_sale=1 AND g.shop_id=s.id AND s.user_id=u.id AND u.rank_id=ur.id  ".$sql,
			'order' => '',
			'limit' => '10', 
            'group' => '',			
			'url' => preg_replace("/&page=([^&]+)/","",$url_this),
			'page' => $page,'plist' => 6,
			'startPage' => true,'DbConfig' => null
		    ) ;			
		
/* 	        $sql = "SELECT g.pv,g.is_set_image,g.brand_id,g.transport_price,g.transport_template_price,g.goods_thumb,g.id as goods_id,g.cat_id,g.goods_name,g.goods_price,g.goods_intro,g.shop_id,s.id as shop_id,s.shop_name,s.user_id,u.id as user_id,u.rank_id,ur.id as rank_id,ur.rank_name,
			s.shop_province,s.shop_city	FROM `$t_goods` AS g,`$t_user` AS u,`$t_shop_info` AS s,`$t_user_rank` AS ur WHERE g.lock_flg<>1 and g.cat_id IN ($catids) AND g.is_on_sale=1 AND g.shop_id=s.id AND s.user_id=u.id AND u.rank_id=ur.id "; */
        }
        if ($brand_id>0) {
	        $tb['conditions'].=" AND g.brand_id='$brand_id'";
        }
	    if ($min_price) {
		    $tb['conditions'].=" AND g.goods_price>'$min_price' ";
	    }
	    if ($max_price) {
		    $tb['conditions'].=" AND g.goods_price<'$max_price' ";
	    }
	    if ($province) {
		    $tb['conditions'].=" AND s.shop_province='$province' ";
	    }
	    if ($country) {
		    $tb['conditions'].=" AND s.shop_country='$country' ";
	    }
	    if ($city) {
		    $tb['conditions'].=" AND s.shop_city='$city' ";
	    }
	    if ($district) {
		    $tb['conditions'].=" AND s.shop_district='$district' ";
	    }		
	    if ($suppid) {
		    $tb['conditions'].=" AND g.supplier_user_id='$suppid' ";
	    }
	
        $k=Request::get_args("k");
        $kk=$k;

	    if ($k&&$k!="请输入你要搜索的关键字") {
		    $tag_sql="SELECT distinct goods_id FROM ".$this->goods->tablePrefix."tag as t WHERE tag_name LIKE '%$k%'";
		    $tag_list = $this->goods->query($tag_sql);
		    foreach ($tag_list as $key=>$v){
			    $tag_list[$key]=$v['t']['goods_id'];
		    }
		    $goods_sql="SELECT distinct id FROM ".$this->goods->tablePrefix."goods as g WHERE goods_name LIKE '%$k%'";
		    $goods_list = $this->goods->query($goods_sql);
		    foreach ($goods_list as $key2=>$v2){
			    $goods_list[$key2]=$v2['g']['id'];
		    }
		    $goods_ids=implode(",",$goods_list);
		    $goods_ids .= implode(",",$tag_list);
		    $arr = explode(",",$goods_ids);
		    $arr = array_unique($arr);
		    $goods_ids = implode(",",$arr);
		    if($goods_ids==""){
			    $goods_ids="0";
		    }
		    $tb['conditions'].=" AND g.id IN ($goods_ids) ";
            //$k_sql="select * from $t_keywords_count where keywords='$k'";
            //$id_row=$dbo->getRow($k_sql);

	    }else{
		    $kk='无';
	    }

        if($_POST){
	        $order_name=$_POST['name'];
	        $order=$_POST['order'];
	        if($order_name){
		        $tb['order']= " g.$order_name $order,g.pv DESC ";
	        }else{
		        $tb['order']= " g.pv DESC ";
	        }
        }else{
	        $tb['order']= " g.goods_price asc,g.pv DESC ";
        }
	    if ($up_price) {
		    $tb['order']=" g.goods_price asc ";
	    }	
	    if ($down_price) {
		    $tb['order']=" g.goods_price desc ";
	    }	
		
	    if ($pv) {
		    $tb['order']=" g.pv desc ";
	    }	
	    if ($fpv) {
		    $tb['order']=" g.favpv desc ";
	    }			
	    if ($new) {
		    $tb['order']=" g.id desc ";
	    }	
 	    $result =  $this->fetch_page($tb);		
        /* 属性 */
        $sql = "select * from ".$this->goods->tablePrefix."attribute as a where cat_id='$cat_id' order by sort_order ";
        $attr_info = $this->goods->query($sql);
        foreach($attr_info as $key => $value){
	        $values_after=str_replace(array("\r\n","\r","\n"),',',$value['a']['attr_values']);
	        $attr_info[$key]['a']['attr_values']=explode(',',$values_after);
	        foreach($attr_info[$key]['a']['attr_values'] as $k => $va){
		        $va=trim($va);
		        $sql = "select count(*) AS attr_count from ".$this->goods->tablePrefix."goods_attr AS ga, ".$this->goods->tablePrefix."goods AS g where ga.attr_values='$va' and g.is_on_sale=1 and	g.id=ga.goods_id ";
		        $goods_attr_info = $this->goods->query($sql);
		        $attr_info[$key]['a']['values_count'][$k]=$goods_attr_info['0']['0']["attr_count"];
	        }
        }

        //品牌列表
        $sql = "SELECT distinct brand_id FROM ".$this->goods->tablePrefix."brand_category as bc WHERE category_id='$cat_id'";
        $list = $this->goods->query($sql);

        $brand_list=array();
        if (is_array($list)) {
	        foreach ($list as $value){
		        $sql="SELECT id,brand_name FROM ".$this->goods->tablePrefix."brand as b WHERE id='{$value['bc']['brand_id']}'";
		        $row=$this->goods->query($sql);
		        $brand_list[$row['0']['b']['id']]['brand_id']=$row['0']['b']['id'];
		        $brand_list[$row['0']['b']['id']]['brand_name']=$row['0']['b']['brand_name'];
		        if(Request::get_args('brand_id')){
        	        $url = preg_replace("/brand_id=([^&]+)/","brand_id=".$row['0']['b']['id'],$url_this);
                }else{
        	        $url = $url_this."&brand_id=".urlencode($row['0']['b']['id']);
		        }
		        $brand_list[$row['0']['b']['id']]['url']=$url;
	        }
        }
        array_push($brand_list,array("brand_id"=>0,"brand_name"=>"全部","url"=>preg_replace("/&brand_id=([^&]+)/","",$url_this)));
		
        $brand_list = array_reverse($brand_list);		
        $nav_selected =4;
		$sub_category=array();
		$temparr = $this->goodscategories->find('all');
		if($temparr) {
            $index = 0;
            while (1){
                foreach ($temparr AS $row){
                    if ($cat_id == $row['goodscategories']['id']){
                        $cat_id = $row['goodscategories']['parent_id'];
                        $sub_category[$index]['cat_id']   = $row['goodscategories']['id'];
                        $sub_category[$index]['cat_name'] = $row['goodscategories']['cat_name'];
                        $sub_category[$index]['url'] = Router::url('default/productlist1/')."?id={$row['goodscategories']['id']}";
                        $index++;
                        break;
                    }
                }
                if ($index == 0 || $cat_id == 0){
                    break;
                }
            }
            $sub_category=array_reverse($sub_category);		
		}
		
        $tag_list = array();
        $tag_list = $this->goods->query("SELECT * FROM ".$this->goods->tablePrefix."tag t WHERE is_recommend=1  group by tag_name  ORDER BY short_order ASC,tag_num DESC limit 15 ");		
	    foreach ($tag_list as $k=>$v){
		    $tag_list[$k]['url']="search.php?k=".urlencode($v['tag_name']);
		    $tag_num = $this->goods->query("select count(tag_name) as num from `".$this->goods->tablePrefix."tag` where tag_name='$v[tag_name]'");
		    $tag_list[$k]['tag_num'] = $tag_num;
	    }		
	    $this->set('brand_list',$brand_list);
	    $this->set('brand_id',$brand_id);		
	    $this->set('attr_info',$attr_info);	
	    $this->set('sub_category',$sub_category);	
	    $this->set('url_this',$url_this);		
	    $this->set('k',$k);
	    $this->set('keyworld',$k);		
	    $this->set('cat_id',$cat_idd);	
	    $this->set('page',$page);			
	    $this->set('result',$result);			
	    $this->set('areainfo',$areainfo);
	    $this->set('CATEGORY',$CATEGORY);
	    $this->set('result',$result);

	    $this->set('min_price',$min_price);
	    $this->set('max_price',$max_price);
	    $this->set('province',$province);
	    $this->set('city',$city);	
	    $this->set('suppid',$suppid);	
	}	


}
?>